﻿#include "mysocket.h"
#include "myserver.h"
#include <QThread>
#include <QDebug>
#include "mainwindow.h"

#if _MSC_VER >=1600
#pragma execution_character_set("utf-8")
#endif

MySocket::MySocket(QObject *parent)
{
    //将父类指针转化为MyServer*类型
    this->m_tcpServer=static_cast<MyServer*>(parent);
}
MySocket::~MySocket()
{
  qDebug()<<"释放Socket,所在线程："<<QThread::currentThreadId();
}

void MySocket::deal_readyRead()
{
    MySocket* tcpsocket=static_cast<MySocket*>(sender());
    //获取客户端IP地址,端口号
    QString ip = tcpsocket->peerAddress().toString();
    quint16 port = tcpsocket->peerPort();
    //获取客户端发来的数据
    QByteArray ba = tcpsocket->readAll();
    //读取时间
    QDateTime curDateTime=QDateTime::currentDateTime();
    QString bas=QString(curDateTime.toString("\r\n yyyy-MM-dd hh:mm:ss ddd")+"从[%1:%2]收到报文：<---\r\n").arg(ip).arg(port);
    QString s;
    ByteToHexString(s,ba);
    //发送到UI线程解析
    emit revcMsg(ba);
    emit AddMessage(bas.toUtf8()+s.toUtf8().toUpper());
}
//发送数据
void MySocket::deal_write(QByteArray ba)
{
    this->write(ba);
}
void MySocket::deal_disconnect()
{
    MySocket* tcpsocket=static_cast<MySocket*>(sender());
    //断开socket
    tcpsocket->abort();
    //消息提示断开
    QString ip = tcpsocket->peerAddress().toString();
    quint16 port = tcpsocket->peerPort();
    QDateTime curDateTime=QDateTime::currentDateTime();
    //发送到UI线程显示
    QString ba=QString(curDateTime.toString("yyyy-MM-dd hh:mm:ss ddd")+"[%1:%2] 已断开--->").arg(ip).arg(port);
    emit AddMessage(ba.toUtf8());
    //断开所有信号连接
    tcpsocket->disconnect();
    //发送到UI线程移除信息
    emit this->sockethelper->RemoveList(tcpsocket);
    //释放
    tcpsocket->deleteLater();
}
